package com.lagou.common.rpc;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

public class JsonDecoder extends ByteToMessageDecoder {
    private final Charset charset;

    public JsonDecoder() {
        this(Charset.defaultCharset());
    }

    public JsonDecoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        } else {
            this.charset = charset;
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)  {
            String objectString = msg.toString(this.charset);
            Object o = JSON.parseObject(objectString, RpcData.class);
            out.add(o);
            msg.skipBytes(msg.readableBytes());

    }
}
